package com.example.publish_model.pushorpull;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.common.mvvm.view.BaseActivity;
import com.example.publish_model.ConsumerGift;
import com.example.publish_model.MsgCallBack;
import com.example.publish_model.R;
import com.example.publish_model.WebSocketService;
import com.example.publish_model.databinding.ActivityPushBinding;
import com.example.publish_model.entity.GifMsgEntity;
import com.example.publish_model.entity.MsgEntity;
import com.example.publish_model.entity.PopMsgEntity;
import com.example.publish_model.entity.TextMsgEntity;
import com.example.publish_model.pushorpull.adapter.PushMsgAdapter;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

public class PushActivity extends BaseActivity<ActivityPushBinding, SendMsgViewModel> implements MsgCallBack,
        View.OnClickListener, FaceFragment.OnEmojiClickListener {
    private WebSocketService socketService;
    private ConnectionBind connectionBind;
    private Button pushSendBtn;
    private EditText pushSendMsgEdit;
    private RecyclerView pushCommentRv;
    private List<String> msgList = new ArrayList<>();
    private PushMsgAdapter pushMsgAdapter;
    boolean flag = true;
    private TextView pushEmojiBtn;
    private FaceFragment faceFragment;
    private FrameLayout emojiContainer;
    private SVGAImageView pushSvga;
    private SVGAParser svgaParser;
    private BlockingQueue<String> blockingQueue;
    private ImageView pushGiftBtn;
    //礼物弹窗监听器
    private PopWindowListener popWindowListener;

    @Override
    protected String pageName() {
        return "PushActivity";
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(this, WebSocketService.class));
        connectionBind = new ConnectionBind();
        bindService(new Intent(this, WebSocketService.class), connectionBind, BIND_AUTO_CREATE);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connectionBind);
        stopService(new Intent(this, WebSocketService.class));
    }

    @Override
    public View bindLayout() {
        return v.getRoot();
    }

    @Override
    public ViewBinding initBind() {
        return ActivityPushBinding.inflate(inflater);
    }

    @Override
    public void initView() {
        //初始化控件
        pushSendBtn = v.pushSendBtn;
        pushSendMsgEdit = v.pushSendMsgEdit;
        pushCommentRv = v.pushCommentRv;
        pushEmojiBtn = v.pushEmojiBtn;
        emojiContainer = v.emojiContainer;
        pushSvga = v.pushSvga;
        pushGiftBtn = v.pushGiftBtn;
        pushSvga.setLoops(1);
        pushSvga.setCallback(new SVGACallback() {
            @Override
            public void onPause() {

            }

            @Override
            public void onFinished() {
                if (!pushSvga.isAnimating()) {
                    ConsumerGift consumerGift = new ConsumerGift(blockingQueue, pushSvga, svgaParser);
                    new Thread(consumerGift).start();
                }

            }

            @Override
            public void onRepeat() {

            }

            @Override
            public void onStep(int i, double v) {

            }
        });

        //礼物SVGA初始化
        svgaParser = SVGAParser.Companion.shareParser();
        svgaParser.init(this);


    }

    @Override
    public void initData() {
        setOnClickListener();

        pushMsgAdapter = new PushMsgAdapter();
        pushCommentRv.setLayoutManager(new LinearLayoutManager(pushCommentRv.getContext(), RecyclerView.VERTICAL, false));
        pushCommentRv.setAdapter(pushMsgAdapter);
        faceFragment = FaceFragment.Instance();
        getSupportFragmentManager().beginTransaction().add(R.id.emoji_Container, faceFragment).hide(faceFragment).commit();

        blockingQueue = new ArrayBlockingQueue<String>(1);
        popWindowListener = new PopWindowListener();
    }

    private void setOnClickListener() {
        pushGiftBtn.setOnClickListener(this);
        pushSendBtn.setOnClickListener(this);
        pushEmojiBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.push_send_btn) {

            String string = pushSendMsgEdit.getText().toString();
            vm.sendMsg(0, string);
            pushSendMsgEdit.setText("");
        } else if (id == R.id.push_emoji_btn) {
            if (flag) {
                flag = !flag;

                getSupportFragmentManager().beginTransaction().show(faceFragment).commit();
                emojiContainer.setVisibility(View.VISIBLE);

            } else {
                flag = !flag;
                getSupportFragmentManager().beginTransaction().hide(faceFragment).commit();
                emojiContainer.setVisibility(View.INVISIBLE);

            }
        } else if (id == R.id.push_gift_btn) {
            //礼物弹出页面
            PopupWindow popupWindow = new PopupWindow();
            popupWindow.setOutsideTouchable(true);
            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ConvertUtils.dp2px(230));
            View inflate = LayoutInflater.from(PushActivity.this).inflate(R.layout.item_gift_list, null, false);
            inflate.setAlpha(0.9f);
            popupWindow.setContentView(inflate);

            View item_gift_list_voice = inflate.findViewById(R.id.item_gift_list_voice);
            View item_gift_list_chigua = inflate.findViewById(R.id.item_gift_list_chigua);
            View item_gift_list_baoji = inflate.findViewById(R.id.item_gift_list_baoji);
            View item_gift_list_love = inflate.findViewById(R.id.item_gift_list_love);
            View item_gift_list_coke = inflate.findViewById(R.id.item_gift_list_coke);

            item_gift_list_chigua.setOnClickListener(popWindowListener);
            item_gift_list_voice.setOnClickListener(popWindowListener);
            item_gift_list_baoji.setOnClickListener(popWindowListener);
            item_gift_list_love.setOnClickListener(popWindowListener);
            item_gift_list_coke.setOnClickListener(popWindowListener);


//            setPopupWindowListener(inflate);
            popupWindow.showAtLocation(getWindow().getDecorView().getRootView(), Gravity.BOTTOM, 0, 0);


        }
    }

    private void setPopupWindowListener(View inflate) {
//        inflate.findViewById(R.id.item_gift_list_voice).setOnClickListener(popWindowListener);
//        inflate.findViewById(R.id.item_gift_list_chigua).setOnClickListener(popWindowListener);
//        inflate.findViewById(R.id.item_gift_list_baoji).setOnClickListener(popWindowListener);
//        inflate.findViewById(R.id.item_gift_list_love).setOnClickListener(popWindowListener);
//        inflate.findViewById(R.id.item_gift_list_coke).setOnClickListener(popWindowListener);
    }



    private class ConnectionBind implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WebSocketService.WebSocketBinder webSocketBinder = (WebSocketService.WebSocketBinder) service;
            socketService = webSocketBinder.getWebSocketService();
            socketService.setMsgCallBack(PushActivity.this::msgCall);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
    //webSocket回调
    @Override
    public void msgCall(MsgEntity msgEntity) {
        if (msgEntity.type == 0) {
            TextMsgEntity textMsgEntity = (TextMsgEntity) msgEntity;
            LogUtils.e("msgCall:" + textMsgEntity.msg);
            if (msgList.size() >= 20) {
                msgList.remove(0);
            }
            msgList.add(textMsgEntity.msg);
            pushMsgAdapter.getData().clear();
            pushMsgAdapter.setNewInstance(msgList);

        } else if (msgEntity.type == 1) {
            PopMsgEntity popMsgEntity = (PopMsgEntity) msgEntity;
        } else if (msgEntity.type == 2) {
            GifMsgEntity gifMsgEntity = (GifMsgEntity) msgEntity;
            ProducerGift producerGift = new ProducerGift(blockingQueue, gifMsgEntity.gifId);
            new Thread(producerGift).start();

            LogUtils.e("pushSvga.isAnimating()" + pushSvga.isAnimating());
            if (!pushSvga.isAnimating()) {
                ConsumerGift consumerGift = new ConsumerGift(blockingQueue, pushSvga, svgaParser);
                new Thread(consumerGift).start();

            }

        }
    }



    @Override
    public void receiveData(Map<String, Object> data) {

    }


    @Override
    public void onEmojiDelete() {
        String text = pushSendMsgEdit.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                pushSendMsgEdit.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                displayTextView();
                return;
            }
            pushSendMsgEdit.getText().delete(index, text.length());
            displayTextView();
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        pushSendMsgEdit.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        displayTextView();
    }


    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = pushSendMsgEdit.getSelectionStart();
            Editable editable = pushSendMsgEdit.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
        }

        displayTextView();
    }

    private void displayTextView() {
        try {
            EmojiUtil.handlerEmojiText(pushSendMsgEdit, pushSendMsgEdit.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public class PopWindowListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.item_gift_list_voice){
                vm.sendMsg(2, "posche.svga");

            }else if (id == R.id.item_gift_list_chigua){
                vm.sendMsg(2, "EmptyState.svga");

            }else if (id == R.id.item_gift_list_baoji){
                vm.sendMsg(2, "jojo_audio.svga");

            }else if (id == R.id.item_gift_list_love){
                vm.sendMsg(2, "heartbeat.svga");

            }else if (id == R.id.item_gift_list_coke){
                vm.sendMsg(2, "MerryChristmas.svga");

            }
        }
    }
}
